package hiho.ku._1062;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
	
	private static class Node {
		String parent;
		int mark;
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		
		int n = in.nextInt();
		Map<String, Node> parent = new HashMap<String, Node>();
		for (int i = 0; i < n; i++) {
			String f = in.next();
			String k = in.next();
			Node node = new Node();
			node.parent = f;
			parent.put(k, node);
		}
		
		int m = in.nextInt();
		for (int i = 1; i <= m; i++) {
			String a = in.next();
			String b = in.next();
			while (parent.containsKey(a)) {
				parent.get(a).mark = i;
				a = parent.get(a).parent;
			}
			while (parent.containsKey(b)) {
				if (parent.get(b).mark == i)
					break;
				b = parent.get(b).parent;
			}
			if (parent.containsKey(b) || b.equals(a))
				System.out.println(b);
			else				
				System.out.println(-1);
		}
	}

}
